package com.heima.tlias.controller;

import com.heima.tlias.service.FileService;
import com.heima.tlias.utils.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@Slf4j
@RequiredArgsConstructor
public class FileUploadController {

    private final FileService fileService;

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping(path = "/upload")
    public Result<String> upload2(@RequestParam("file") MultipartFile file) throws IOException {
        String readPath = fileService.upload(file);
        return Result.success(readPath);
    }

    /**
     * 文件上传 --- 上传到本地
     *
     * @param username
     * @param age
     * @param file
     * @return
     */
    //@PostMapping(path = "/upload1")
    public Result<String> upload1(String username, String age, @RequestParam("file") MultipartFile file) throws IOException {
        log.info("接收到文件上传的普通参数,username:{},age:{}", username, age);
        //文件数据处理
        //1. 获取原始文件名称
        String originalFilename = file.getOriginalFilename();
        //2. 判断文件数据是否存在
        boolean empty = file.isEmpty();
        System.out.println("是否存在:" + empty);
        //3. 获取文件类型
        String contentType = file.getContentType();
        System.out.println("文件类型:" + contentType);
        //4. 获取文件字节流
        byte[] bytes = file.getBytes();
        System.out.println("文件字节数组:" + bytes);
        //5. 获取文件大小
        long size = file.getSize();
        System.out.println("文件大小:" + size);
        //2. 获取文件输入流数据
        //InputStream inputStream = file.getInputStream();
        //3. 将文件流数据写到磁盘上
        //FileOutputStream outputStream = new FileOutputStream();
        //outputStream.write(inputStream.readAllBytes());
        //outputStream.flush();
        //outputStream.close();
        //inputStream.close();   12313.1311
        //唯一文件名称: uuid , 文件的散列值 , 时间戳毫秒值 + 随机值   ASDADADASDADSADADADADA.jpg
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        //传输文件数据到指定文件 F:\系统资料\桌面\file\ 2024\05\17
        String dir = "F:\\系统资料\\桌面\\file\\" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        file.transferTo(new File(dir, fileName));

        return Result.success("文件上传成功");
    }
}
